package com.nakamachizu.controller.mixi;

import java.util.logging.Logger;

import net.arnx.jsonic.JSON;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.nakamachizu.model.mixi.PersonFriendsModel;
import com.nakamachizu.model.session.MixiSessionData;
import com.nakamachizu.service.MapDataService;
import com.nakamachizu.service.mixi.RestfulService;
import com.nakamachizu.util.ErrorsUtil;

public class FriendController extends Controller {

    private static final Logger log = Logger.getLogger(FriendController.class.getName());
    
    private String sid;
    
    @Override
    public Navigation run() throws Exception {
        
        sid = requestScope("sid");
        
        MapDataService mds = new MapDataService();
        MixiSessionData session = mds.getMixiSessionData(sid);
        if(session.isOwner()){
            RestfulService service = new RestfulService();
            service.makeSignature(session.getViewerId(),
                RestfulService.TARGET_UID_ME,
                RestfulService.TARGET_TYPE_FRIENDS,
                RestfulService.FORMAT_JSON,
                RestfulService.DEFAULT_COUNT,
                RestfulService.DEFAULT_START_INDEX);
            int result = service.request();
            if(result == 200){
                PersonFriendsModel model = JSON.decode(service.getContents(), PersonFriendsModel.class);
            }else{
                StringBuilder buf = new StringBuilder("Contents:").append(service.getContents()).append("\n\n");
                for(HTTPHeader header : service.getHttpHeader()){
                    buf.append(header.getName()).append(":").append(header.getValue()).append("\n");
                }
                log.severe(buf.toString());
                return forward("/jsp/pc/mixi/error.jsp");
            }
            
        }
        

        
        return forward("/jsp/pc/mixi/friend.jsp");
    }
    
    @Override
    protected Navigation handleError(Throwable error) {
        error.printStackTrace();
        log.severe(ErrorsUtil.stackTrace(error));
        return forward("/jsp/pc/mixi/error.jsp");
    }
}
